package com.ramos.kuaixiao.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.ui.BrandInfoActivity;
import com.ramos.kuaixiao.ui.SpaceImageDetailActivity;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProductResultAdapter extends RecyclerView.Adapter implements Filterable {

    private List<ShopTypeBean.ShopType.ProductInfo> tasklist;
    private Activity activity;
    private ArrayList<ShopTypeBean.ShopType.ProductInfo> mOriginalValues;
    private final Object mLock = new Object();
    private String keyWrold = ""; // 关键字
    UpdateCarListener updateListener;
    Customer mCustomer;

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView id;
        TextView warehouse;
        TextView price;
        ImageView productImg;
        TextView barcodeText;
        LinearLayout ll_product;

        public ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.brand_name);
            id = (TextView) itemView.findViewById(R.id.brand_id);
            warehouse = (TextView) itemView.findViewById(R.id.brand_warehouse);
            price = (TextView) itemView.findViewById(R.id.brand_price);
            productImg = (ImageView) itemView.findViewById(R.id.productImg);
            barcodeText = (TextView) itemView.findViewById(R.id.barcodeText);
            ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
        }

        public void setVisibile(boolean visible) {
            RecyclerView.LayoutParams param = (RecyclerView.LayoutParams) itemView.getLayoutParams();
            if (visible) {
                param.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                param.width = LinearLayout.LayoutParams.MATCH_PARENT;
                itemView.setVisibility(View.VISIBLE);
            } else {
                itemView.setVisibility(View.GONE);
                param.height = 0;
                param.width = 0;
            }
            itemView.setLayoutParams(param);
        }
    }

    public ProductResultAdapter(Activity context, List<ShopTypeBean.ShopType.ProductInfo> hotcourse, Customer customer) {
        this.activity = context;
        this.tasklist = hotcourse;
        mCustomer = customer;
        initImage(tasklist);
    }

    private void initImage(List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
        Product product = new Product(tasklist);
        product.executeOnExecutor(Executors.newCachedThreadPool());
    }

    public void refresh(List<ShopTypeBean.ShopType.ProductInfo> data) {
        tasklist = data;
        initImage(tasklist);
    }

    @Override
    public int getItemCount() {
        return tasklist.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(activity).inflate(R.layout.listitem_product, null);
        ViewHolder vh = new ViewHolder(view);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);
        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
        final ViewHolder holder = (ViewHolder) viewHolder;
        showText(tasklist.get(position).getProductInfoName(), holder.name);
        showText(tasklist.get(position).getProductInfoId(), holder.id);
        int param = new StoreNumDB().getParam(tasklist.get(position).getProductInfoId());
        holder.warehouse.setText(getStore(tasklist.get(position).getTotal(), param));
        if (StringUtil.isEmpty(tasklist.get(position).getNonTaxSalePrice())/*  || Double.valueOf(tasklist.get(position).getNonTaxSalePrice()) == 0
               ||(!SharedPreference.getPreferBoolean("isAllShop") && tasklist.get(position).getTotal() == 0)*/) {
            holder.setVisibile(false);
        } else {
            holder.setVisibile(true);
            holder.price.setVisibility(View.VISIBLE);
            holder.price.setText("￥" + App.df.format(Double.valueOf(tasklist.get(position).getNonTaxSalePrice())));
            if(tasklist.get(position).getType() == 1){
                holder.price.setTextColor(activity.getResources().getColor(R.color.red));
            } else {
                holder.price.setTextColor(activity.getResources().getColor(R.color.black));
            }
        }
        Log.d("Product", "tasklist.get(position).getIconUrl() " + position + " " + tasklist.get(position).getIconUrl()
                + " " + tasklist.get(position).getProductInfoName() + " " + tasklist.get(position).getProductInfoId() + " "
                + tasklist.get(position).getTotal() + " " + tasklist.get(position).getNonTaxSalePrice());
        Utils.glideImage(tasklist.get(position).getIconUrl(), holder.productImg);
        final int width = holder.productImg.getWidth();
        final int height = holder.productImg.getHeight();
        final int[] location = new int[2];
        holder.productImg.getLocationOnScreen(location);

        holder.productImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(activity, width, height, location, tasklist.get(position).getIconUrl());
            }
        });
        holder.barcodeText.setText(Utils.getText(tasklist.get(position).getProductBarCode()));

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShopTypeBean.ShopType.ProductInfo brand = tasklist.get(position);
                if(brand.getType() == 1) {
                    Intent intent = new Intent(activity, BrandInfoActivity.class);
                    intent.putExtra("brand", brand);
                    intent.putExtra("customer", mCustomer);
                    activity.startActivity(intent);
                } else {
                    ToastUtils.show("此商品未关联价格套，无法下单");
                }
            }
        });
    }

    private String getStore(int count, int param) {
        String store;
        if (count == 0 || param == 0) {
            store = "0箱0支";
        } else {
            int box = count / param;
            int single = count % param;
            store = box + "箱" + single + "支";
        }
        return store;
    }


    private void showImage(Activity actiivty, int width, int height, int[] location, String iconUrl) {
        Intent intent = new Intent(actiivty, SpaceImageDetailActivity.class);
        intent.putExtra("images", iconUrl);
        intent.putExtra("locationX", location[0]);
        intent.putExtra("locationY", location[1]);
        intent.putExtra("width", width);
        intent.putExtra("height", height);
        actiivty.startActivity(intent);
        actiivty.overridePendingTransition(0, 0);
    }

    private void showText(String str, TextView textView) {
        //textView.clearComposingText();
        if (!keyWrold.equals("")) {
            String patten = "" + keyWrold;
            Pattern p = Pattern.compile(patten);
            Matcher m = p.matcher(str);
            SpannableString spannableString = new SpannableString(str);
            while (m.find()) {
                if (str.contains(m.group())) {
                    spannableString.setSpan(
                            new ForegroundColorSpan(0xffec8b44), m.start(),
                            m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            textView.setText(spannableString);
        } else {
            textView.setText(str);
        }
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        return filter;
    }

    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tasklist = (List<ShopTypeBean.ShopType.ProductInfo>) results.values;
            if (results.count > 0) {
                initImage(tasklist);
                notifyDataSetChanged();
                notifyListeners(results.count, tasklist);
            } else {
                notifyListeners(0, tasklist);
                notifyDataSetChanged();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            // TODO Auto-generated method stub
            FilterResults filterResults = new FilterResults();

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    //mOriginalValues = new ArrayList<>(tasklist);
                    Log.d("product", "App.mProductInfos" + App.mProductInfos.size());
                    mOriginalValues = new ArrayList<>(App.mProductInfos);//全部产品模糊搜索
                }
            }
            Log.d("product", "mOriginalValues" + mOriginalValues.size());
            if (prefix == null || prefix.length() == 0) {
                ArrayList<ShopTypeBean.ShopType.ProductInfo> list;
                synchronized (mLock) {
                    list = new ArrayList<>(mOriginalValues);
                }
                filterResults.values = list;
                filterResults.count = list.size();
                keyWrold = "";
            } else {
                String prefixString = prefix.toString().toLowerCase();
                ArrayList<ShopTypeBean.ShopType.ProductInfo> values;
                synchronized (mLock) {
                    values = new ArrayList<>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<ShopTypeBean.ShopType.ProductInfo> newValues = new ArrayList<>();

                for (int i = 0; i < count; i++) {
                    ShopTypeBean.ShopType.ProductInfo value = values.get(i);
                    // First match against the whole, non-splitted value
                    boolean hasName = hasValue(value.getProductInfoName(), prefixString);
                    boolean hasId = hasValue(value.getProductInfoId(), prefixString);
                    boolean hasBar = hasValue(value.getProductBarCode(), prefixString);
                    boolean hasType = hasValue(value.getProductTypeName(), prefixString);
                    boolean hasBrand = hasValue(value.getBrandName(), prefixString);
                    if (hasName || hasId || hasBar || hasType || hasBrand) {
                        newValues.add(value);
                        keyWrold = prefixString;
                    }
                }
                filterResults.values = newValues;
                filterResults.count = newValues.size();
                Log.d("product", "count:" + count);
            }
            return filterResults;
        }
    };

    private boolean hasValue(String productInfoName, String prefixString) {
        if (StringUtil.isEmpty(productInfoName)) {
            return false;
        } else {
            if (productInfoName.toLowerCase().contains(prefixString)) {
                return true;
            }
        }
        return false;
    }


    private void notifyListeners(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
        updateListener.update(num, tasklist);
    }

    public interface UpdateCarListener {
        void update(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist);
    }

    public void setUpdateCarListener(UpdateCarListener updateListener) {
        this.updateListener = updateListener;
    }

    class Product extends AsyncTask<String, String, String> {
        List<ShopTypeBean.ShopType.ProductInfo> list;

        public Product(List<ShopTypeBean.ShopType.ProductInfo> type) {
            list = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < list.size(); i++) {
                    Log.d("product", "doInBackground:" + i + " " + list.size());
                    ShopTypeBean.ShopType.ProductInfo productInfo = list.get(i);
                    String imgURL = Utils.showImg(productInfo.getProductInfoId(), productInfo.getProductBarCode());
                    if (!StringUtil.isEmpty(imgURL)) {
                        productInfo.setIconUrl(imgURL);
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            //refresh(list);
            notifyDataSetChanged();
        }
    }
}